import pandas as pd
import matplotlib.pyplot as plt
import textwrap
from matplotlib.font_manager import FontProperties

plt.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文
plt.rcParams['axes.unicode_minus']=False 

#FILE_PATH = r'C:\Users\ZhuanZ\Desktop\result\old5000.xlsx'
FILE_PATH = r'C:\Users\ZhuanZ\Desktop\result\TLS_CA.xlsx'
try:
    df = pd.read_excel(FILE_PATH, engine='openpyxl')
    # print(df.columns)
except FileNotFoundError:
    print("File not found. Please check the file path.")
except Exception as e:
    print(f"An error occurred while reading the file: {e}")
    
matching_rows = []  
  
for index, row in df[df['方案'] == '旧'].iterrows():  
    operation = row['操作']  
    algorithm = row['签名']  
  
    # 检查操作是否以 'verify' 开头  
    if operation.startswith('verify'):  
        matching_new_rows = df[(df['操作'] == operation) & (df['签名'] == algorithm) &  
                               (df['方案'] != '旧')]  # 这里用 != '5K' 来排除当前的消息长度  

        if not matching_new_rows.empty:  
            for new_row in matching_new_rows.itertuples(index=False):  
                matching_rows.append((row, new_row))   
        
'''
for old_row, new_row in matching_rows:  
    print(f"旧算法行: 消息长度 = {old_row['消息长度']}bit,平均时间={old_row['平均时间 ']}us, 签名长度={old_row['签名长度']}bit")  
    print(f"新算法行: 消息长度 = {new_row[0]}bit,平均时间={new_row[5]}us, 签名长度={new_row[9]}bit")  # 假设新行的迭代次数和签名长度位于第3和第4个位置
    print("-" * 40)
'''

operation_names = [old_row['操作'] for old_row, _ in matching_rows]
old_CAsize = [old_row['数字证书大小'] for old_row, _ in matching_rows]
new_CAsize = [new_row[3] for _, new_row in matching_rows]
handshake_time = [old_row['签名'] for old_row, _ in matching_rows]
old_HStime = [old_row['握手平均时间'] for old_row, _ in matching_rows]
new_HStime = [new_row[4] for _, new_row in matching_rows]

# 创建图表  
fig, ax1 = plt.subplots(figsize=(15, 10))

# 绘制平均时间图表
index = list(range(len(operation_names)))
bar_width = 0.35
offset = bar_width / 2
# 合并条形图
for i, pos in  enumerate(index):
    #ax1.bar(pos - offset, old_iteration[i], bar_width, label='原方案 - 平均时间' if i == 0 else '', color='tab:blue')
    #ax1.bar(pos + offset, new_iteration[i], bar_width, label='新方案 - 平均时间' if i == 0 else '', color='tab:red')
    ax1.bar(pos - offset, old_HStime[i], bar_width, label='原方案 - 握手时间' if i == 0 else '', color='tab:blue')
    ax1.bar(pos + offset, new_HStime[i], bar_width, label='新方案 - 握手时间' if i == 0 else '', color='tab:red')

# 设置 x 轴标签
ax1.set_xlabel('算法名称')
ax1.set_ylabel('握手时间（us）')
ax1.tick_params(axis='y', labelcolor='tab:blue')
ax1.set_xticks(index)
wrapped_labels = ['\n'.join(textwrap.wrap(label, width=9)) for label in handshake_time]
ax1.set_xticklabels(wrapped_labels, rotation=0, ha='center')
ax1.set_yscale('linear')

# 添加图例
plt.legend(loc='upper left', ncol=2, fontsize=12, frameon=True)

# 设置图表标题
#plt.title('签名长度比较')
plt.tick_params(axis='x', labelsize=8)

# 显示图表
plt.show()


'''
# 筛选符合条件的行
df_filtered = df[df['消息长度'].isin(['5K', '50', '50K'])]

# 计算每个操作和签名组合的平均时间
grouped = df_filtered.groupby(['操作', '签名'])['时间'].mean().reset_index()

# 准备绘图数据
operations = grouped['操作'].unique()
algorithms = grouped['签名'].unique()
average_times = grouped.pivot(index='操作', columns='签名', values='时间')

# 创建柱状图
plt.figure(figsize=(10, 6))

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用黑体显示中文
plt.rcParams['axes.unicode_minus'] = False

# 绘制柱状图
bar_width = 0.2
index = range(len(operations))

for i, algorithm in enumerate(algorithms):
    values = average_times[algorithm]
    plt.bar([x + i * bar_width for x in index], values, bar_width, label=algorithm)

# 添加标题和标签
plt.xlabel('操作')
plt.ylabel('平均时间')
plt.title('不同操作和签名的平均时间')
plt.xticks([x + (len(algorithms) - 1) * bar_width / 2 for x in index], operations)
plt.legend(title='签名算法')

# 显示图形
plt.show()
'''